<?php
if (!isset($sp)) {
    $sp = explode("/", $_SERVER['PHP_SELF']);
}
if ($_SERVER['HTTP_HOST'] == "localhost" || $_SERVER['HTTP_HOST'] == "192.168.1.34") {
    $sp[1] = '/' . $sp[1];
} else {
    $sp[1] = '';
}
$w_root = $_SERVER['SERVER_NAME'] . $sp[1];
$w_root = str_replace('//', '/', $w_root);
$w_root = str_replace('\\\\', '\\', $w_root);

$s_root = $_SERVER['DOCUMENT_ROOT'] . $sp[1];
$s_root = str_replace('//', '/', $s_root);
$s_root = str_replace('\\\\', '\\', $s_root);
/* ========End Setting up web root and server root ============= */
require_once $s_root . '/social/country.php'; // Country IP
require_once $s_root . '/libraryfiles/config.php';
$config = $s_root . '/hybridauth/config.php';
require_once $s_root . '/hybridauth/Hybrid/Auth.php';
$user_data = NULL;
$return_url = @ $_GET["return_url"];
$login_url = W_ROOT . "/login.php";
if ($return_url == $login_url) {
    $return_url = W_ROOT;
} else {
    $return_url = $return_url;
}

// try to get the user profile from an authenticated provider
try {
    $hybridauth = new Hybrid_Auth($config);
    $connected_adapters_list = $hybridauth->getConnectedProviders();

    // selected provider name
    $provider = @ trim(strip_tags($_GET["provider"]));

    // check if the user is currently connected to the selected provider
    if (!$hybridauth->isConnectedWith($provider)) {
        // redirect him back to login page
        header( "Location: ../login.php?error=Your are not connected to $provider or your session has expired" );
    }

    // call back the requested provider adapter instance (no need to use authenticate() as we already did on login page)
    $adapter = $hybridauth->getAdapter($provider);

    // grab the user profile
    $user_data = $adapter->getUserProfile();
} catch (Exception $e) {
    // In case we have errors 6 or 7, then we have to use Hybrid_Provider_Adapter::logout() to
    // let hybridauth forget all about the user so we can try to authenticate again.
    // Display the recived error,
    // to know more please refer to Exceptions handling section on the userguide
    switch ($e->getCode()) {
        case 0 : echo "Unspecified error.";
            break;
        case 1 : echo "Hybriauth configuration error.";
            break;
        case 2 : echo "Provider not properly configured.";
            break;
        case 3 : echo "Unknown or disabled provider.";
            break;
        case 4 : echo "Missing provider application credentials.";
            break;
        case 5 : echo "Authentification failed. "
            . "The user has canceled the authentication or the provider reused the connection.";
        case 6 : echo "User profile request failed. Most likely the user is not connected "
            . "to the provider and he should to authenticate again.";
            $adapter->logout();
            break;
        case 7 : echo "User not connected to the provider.";
            $adapter->logout();
            break;
    }

    echo "<br /><br /><b>Original error message:</b> " . $e->getMessage();

    echo "<hr /><h3>Trace</h3> <pre>" . $e->getTraceAsString() . "</pre>";
}

if (!empty($_POST['accounttype'])) {
    $user_type = $_POST['accounttype'];
}
$account_from = $adapter->id;
$provider_uid = $user_data->identifier;
$email = $user_data->email;
$first_name = $user_data->firstName;
//for user
// preg_match('/([a-zA-Z0-9\-\._\+]+@[a-z0-9A-Z\-\._]+\.[a-zA-Z]+)/', $email, $regex);
// $handle = array_shift(explode('@', $regex[1]));
// $handle = preg_replace( "#[^a-zA-Z0-9 ]#", "", $handle);
$username = $email;
$last_name = $user_data->lastName;
$display_name = $user_data->displayName;

$website_url = $user_data->webSiteURL;
$profile_url = $user_data->profileURL;
$photo_url = $user_data->photoURL;
$gender = $user_data->gender;
$age = $user_data->age;
$birth_day = $user_data->birthDay;
$birth_month = $user_data->birthMonth;
$birth_year = $user_data->birthYear;
$phone = $user_data->phone;
$address = $user_data->address;
//$country   = $user_data->country;
$country = !empty($country) ? $user_data->country : $ip_country;
$region = $user_data->region;
$city = $user_data->city;
$zip = $user_data->zip;
$password = rand(); # for the password we generate something random
$getCodGeneration = generateRandomString();
if ($gender == 'male') {
    $title = 'Mr.';
} else if ($gender == 'female') {
    $title = 'Miss/Mrs.';
}

$check = mysql_query("SELECT * FROM tbluser WHERE email='$email'") or die(mysql_error());

$sorturl = strtolower($first_name); // if no sort url
$sorturl = str_replace(' ', '-', $sorturl);
if (mysql_num_rows($check) == 0) {
    if (empty($_POST['accounttype'])) {
        header("location:" . W_ROOT . "/create_account.php?provider=" . $provider . "&return_url=" . $return_url);
    } else if (empty($_POST ['first_name'])) {
        $error = $lang ['PLEASE_INPUT_FNAME'];
        header("location:" . W_ROOT . "/create_account.php?provider=" . $provider . "&return_url=" . $return_url."&error=".$error);
        exit();
    } else if (empty($_POST ['last_name'])) {
        $error = 'Please input last name!';
        header("location:" . W_ROOT . "/create_account.php?provider=" . $provider . "&return_url=" . $return_url."&error=".$error);
        exit();
    } else if (empty($_POST ['title'])) {
        $error = 'Please input title!';
        header("location:" . W_ROOT . "/create_account.php?provider=" . $provider . "&return_url=" . $return_url."&error=".$error);
        exit();
    } else if (empty($_POST ['mobile'])) {
        $error = 'Please input mobile phone!';
        header("location:" . W_ROOT . "/create_account.php?provider=" . $provider . "&return_url=" . $return_url."&error=".$error);
        exit();
    } else if (empty($_POST ['email'])) {
        $error = 'Please input e-mail!';
        header("location:" . W_ROOT . "/create_account.php?provider=" . $provider . "&return_url=" . $return_url."&error=".$error);
        exit();
    } else if (empty($_POST ['address'])) {
        $error = 'Please input address!';
        header("location:" . W_ROOT . "/create_account.php?provider=" . $provider . "&return_url=" . $return_url."&error=".$error);
        exit();
    } else if (empty($_POST ['txt_state'])) {
        $error = $lang ['PLEASE_SELECT_PROVINCE'];
        header("location:" . W_ROOT . "/create_account.php?provider=" . $provider . "&return_url=" . $return_url."&error=".$error);
        exit();
    } else if (empty($_POST ['selectionDistrict'])) {
        $error = $lang ['PLEASE_SELECT_DISTRICT'];
        header("location:" . W_ROOT . "/create_account.php?provider=" . $provider . "&return_url=" . $return_url."&error=".$error);
        exit();
    } else {

        /* send email to confirm */
        include_once S_ROOT . '/libraryfiles/SendEmail.php';
        $transport = new SendEmail ();
        $name = $first_name . $last_name;
        $header = 'info.neakporn@gmail.com';
        $subjects = "Psarinternet Activation";
        $base = "http://" . $_SERVER ["SERVER_NAME"];
        if ($user_type == 2) {
            $status = 0;
            $BodyHeader = "YOUR ACCOUNT HAS BEEN REGISTER!";
            $BodyMessage = 'Your account is pending, please wait your activation by psarinternet administrator!';
        } else {
            $status = 0;
            $BodyHeader = "ACTIVATE YOUR ACCOUNT NOW!";
            $BodyMessage = 'Click here to confirm your account: <a href="' . base_url . 'account/confirm.php?confirm=' . $getCodGeneration . '&id=' . $email . '">Active Now!</a> ';
        }
        $transport = $transport->SendMail($name, $email, $base, $header, $subjects, $BodyHeader, $BodyMessage);
        /* end send email to confirm */
        //$transport == TRUE;
        if ($transport == TRUE) {
            $first_name = addslashes($_POST ['first_name']);
            $last_name = addslashes($_POST ['last_name']);
            $title = $_POST ['title'];
            $user_type = (int) $_POST ['accounttype'];
            $mobile = addslashes($_POST ['mobile']);
            $phone = addslashes($_POST ['phone']);
            $email = $_POST ['email'];
            $address = addslashes($_POST ['address']);
            $status = 0;
            $state = $_POST ['txt_state'];
            $country = $_POST ['country_id'];
            $location = $_POST ['selectionDistrict'];
            $newsletter = isset($_POST ['newsletter']) ? $_POST ['newsletter'] : 0;
            $secret_word = isset($_POST ['secret_word']) ? $_POST ['secret_word'] : 0;
            $freeaccount = isset($_POST ['freeaccount']) ? $_POST ['freeaccount'] : '';

            //if (empty($freeaccount)) {
            $com_name = addslashes(@$_POST ['pharmacy_name']);
            $com_address = addslashes(@$_POST ['pharmacy_address']);
            $com_phone = addslashes(@$_POST ['pharmacy_phone']);
            $com_fax = addslashes(@$_POST ['pharmacy_fax']);
            $com_email = @$_POST ['pharmacy_email'];
            $com_website = @$_POST ['pharmacy_website'];
            $com_open_hour = @$_POST ['open_hour'];
            $com_close_hour = @$_POST ['close_hour'];
            $com_license = @$_POST ['pharmacy_license'];
            $data_user = array(
                Tbluser::first_name => $first_name,
                Tbluser::last_name => $last_name,
                Tbluser::title => $title,
                Tbluser::user_pass => $getCodGeneration,
                Tbluser::user_type_id => $user_type,
                Tbluser::account_type_id => 1,
                Tbluser::mobile => $mobile,
                Tbluser::phone => $phone,
                Tbluser::address => $address,
                Tbluser::state_id => $state,
                Tbluser::country_id => $country,
                Tbluser::location => $location,
                Tbluser::email => $email,
                Tbluser::cdate => strtotime(date('d-m-Y h:i:s')),
                Tbluser::mdate => strtotime(date('d-m-Y h:i:s')),
                Tbluser::status => $status,
                Tbluser::newsletter => $newsletter,
                Tbluser::secret_word => $secret_word,
                Tbluser::activate => $getCodGeneration,
                Tbluser::account_type => $provider
            );
            $lastid = insert(Tbluser::Tbluser, $data_user);
            /* end add user by Ngann socheat 2014 */

            /* add company */
            $sorturl = strtolower($first_name); // if no sort url
            $sorturl = str_replace(' ', '-', $sorturl);
            $data_com = array(
                Tblcompany::name => $phone,
                Tblcompany::address => $address,
                Tblcompany::phone => $phone,
                Tblcompany::email => $email,
                Tblcompany::user_id => $lastid,
                Tblcompany::cdate => strtotime(date('d-m-Y h:i:s')),
                Tblcompany::mdate => strtotime(date('d-m-Y h:i:s')),
                Tblcompany::status => 1,
                Tblcompany::shorturl => exist_domain($sorturl)
            );
            $add_company = insert(Tblcompany::tblcompany, $data_com);
            /* end add company by Ngann socheat 2014 */
            //header('Location: ../login.php?success=USER_NOT_ACTIVATE_YET&email=' . $email);
        } else {
            header('Location: ../login.php?error=USER_CANNOT_CREATE');
            exit();
        }
        $new = mysql_query("SELECT * FROM tbluser WHERE email='" . $email . "' AND user_type_id='" . $user_type . "'") or die('error syntam' . mysql_error());
        $rows = mysql_fetch_assoc($new);
        if ($user_type != 2) {
            header("Location: " . base_url . "login.php?success=USER_NOT_ACTIVATE_YET&email=" . $email);
//            $_SESSION['username'] = $rows['email'];
//            $_SESSION['fullname'] = $rows['first_name'] . ' ' . $rows['last_name'];
//            $_SESSION['usertype'] = $rows['user_type_id'];
//            $_SESSION['pass'] = $rows['user_pass'];
//            $_SESSION['province_id'] = $rows[Tbluser::country_id];
//            $_SESSION['disctict_id'] = $rows[Tbluser::state_id];
//            $_SESSION['acc_type'] = $rows['account_type_id'];
            //header("location:" . base_url . "process_login.php?return_url=" . $return_url);
        } else {
            header("location:" . base_url . "index.php?success=USER_WAIT_APROVE");
        }
    }
}
if (mysql_num_rows($check) > 0) {
    $where_user = array(
        Tbluser::email => $email,
        Tbluser::status => 1,
    );
    $user_check = select(Tbluser::Tbluser, array(Tbluser::email, Tbluser::user_pass, Tbluser::status, Tbluser::first_name, Tbluser::last_name, Tbluser::account_type_id, Tbluser::user_type_id, Tbluser::perm, Tbluser::id, Tbluser::state_id, Tbluser::location), $where_user);
    if (dbNumRows($user_check) != 0) {
        $rows = mysql_fetch_assoc($user_check);
        $_SESSION['username'] = $rows['email'];
        $_SESSION['fullname'] = $rows['first_name'] . ' ' . $rows['last_name'];
        $_SESSION['usertype'] = $rows['user_type_id'];
        $_SESSION['pass'] = $rows['user_pass'];
        $_SESSION['province_id'] = $rows[Tbluser::state_id];
        $_SESSION['disctict_id'] = $rows[Tbluser::location];
        $_SESSION['acc_type'] = $rows['account_type_id'];
        header("location:" . W_ROOT . "/process_login.php?return_url=" . $return_url);
    } else {
        header("Location: " . base_url . "login.php?success=USER_NOT_ACTIVATE_YET&email=" . $email);
    }
}

function generateRandomString($length = 50) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters [rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

?>